package com.ajz.security.service.impl;

import java.util.List;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.ajz.common.utils.Collections3;
import com.ajz.security.dao.GroupDao;
import com.ajz.security.dao.UserDao;
import com.ajz.security.entity.Group;
import com.ajz.security.entity.Role;
import com.ajz.security.entity.User;
import com.ajz.security.model.SecurityUser;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;

@Component
@Transactional
public class CustomUserDetailsService implements UserDetailsService {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private UserDao userDao;
	
	@Autowired
	private GroupDao groupDao;
	
//	@Autowired
//	private IStoreInfoService storeInfoService;

	@Override
	public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
		User user = userDao.findByLoginName(userName);
		if (user == null) {
			throw new UsernameNotFoundException("UserName " + userName + " not found");
		}

		Set<Role> userRoles = Sets.newHashSet();
		Set<String> userDataPermissions = Sets.newHashSet();

		if (user.getDataPermission() != null && !user.getDataPermission().isEmpty()) {
			userDataPermissions.addAll(user.getDataPermission());
		}

		// 用户管理分配的角色
		Set<Group> allUserGroups = Sets.newHashSet();
		List<String> userGroups = user.getUserGroups();
		for (String groupId : userGroups) {
			Group group = groupDao.getOne(groupId);
			allUserGroups.add(group);
		}
		
		// 角色管理分配的用户
		List<Group> groups = user.getGroups();
		if (Collections3.isNotEmpty(groups)) {
			allUserGroups.addAll(groups);
		}
		

		for (Group group : allUserGroups) {
//			if (group.getDataPermission() != null && !group.getDataPermission().isEmpty()) {
//				userDataPermissions.addAll(group.getDataPermission());
//			}

			List<Role> roles = group.getRoles();
			for (Role role : roles) {
				getRolesCascade(role, userRoles);
			}
		}

//		dealDataPermissionCascade(userDataPermissions);
		
		 userRoles.addAll(user.getRoles());

		logger.info("登录用户{} 权限 {}", user.toString(), userRoles.toString());

		SecurityUser securityUser = new SecurityUser(user.getId(), user.getName(), user.getLoginName(), user.getPassword(),
				Lists.newArrayList(userRoles));
		securityUser.setDataPermissions(Lists.newArrayList(userDataPermissions));
		securityUser.setType(user.getType());
		return securityUser;
	}

	private void getRolesCascade(Role role, Set<Role> userRoles) {
		Role r = new Role(role.getId(), role.getName(), role.getRemark());
		userRoles.add(r);
//		for (Role childRole : role.getChildren()) {
//			getRolesCascade(childRole, userRoles);
//		}
		if(role.getParent()!=null){
			getRolesCascade(role.getParent(), userRoles);
		}
	}
	
//	private void dealDataPermissionCascade(Set<String> userDataPermissions) {
//		if (userDataPermissions.contains(SecurityUtils.getAllShopid())) {
//			return;
//		}
//		List<String> areaIds = Lists.newArrayList();
//		for (String shopid : userDataPermissions) {
//			if (shopid.length() >= SecurityUtils.getAreaIdCheckLength()) {
//				areaIds.add(shopid);
//			}
//		}
//		
//		if (Collections3.isNotEmpty(areaIds)) {
//			Map<String, Object> searchParams = Maps.newHashMap();
//			searchParams.put("BEGIN_sapynumod", "9");
//			searchParams.put("IN_headshopid", areaIds);
////			Iterable<StoreInfo> storeInfos = storeInfoService.findList(searchParams);
////			for(StoreInfo storeInfo : storeInfos) {
////				if (!userDataPermissions.contains(storeInfo.getSapynumod())) {
////					userDataPermissions.add(storeInfo.getSapynumod());
////				}
////			}
//		}
//	}
}
